package internal

import (
	"context"
	"encoding/json"
	"gitee.com/alex_li/weight/internal/monitor"
	"github.com/lishimeng/go-log"
)

var listener func(name string, data monitor.WeightData)


func Weight(ctx context.Context, name string, rate int) (w *monitor.Weight, err error) {

	//rawListener := func(data monitor.WeightDataRaw) {
	//	fmt.Printf("state:%s, type:%s, data:%s, unit:%s", data.State, data.Type, data.Data, data.Unit)
	//	fmt.Println()
	//}
	//rawListener()
	dataListener := func(name string, data monitor.WeightData) {
		bs, err := json.Marshal(data)
		if err != nil {
			log.Info(err)
			return
		}
		log.Info(string(bs))
	}
	if listener == nil {
		listener = dataListener
	}
	w = monitor.New(name, rate, ctx, nil, listener)
	go func() {
		err := w.Start()
		if err != nil {
			log.Info("open weight fail")
			log.Info(err)
		}
	}()

	return
}
